package com.ruin.tech.ahri.service.impl;

import com.ruin.tech.ahri.dao.*;
import com.ruin.tech.ahri.model.dto.*;
import com.ruin.tech.ahri.model.vo.ArticleVO;
import com.ruin.tech.ahri.service.IArticleService;
import com.ruin.tech.ahri.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * @program ahri
 * @description: 文章操作服务类
 * @author: ruin
 * @create: 2019/12/04 08:26
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    TmpArticleImgMapper tmpArticleImgMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    AppreciateMapper appreciateMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    BrowseMapper browseMapper;

    @Value("${upload.path.coverImg}")
    private String uploadCoverImgPath;

    @Override
    public void saveArticle(Article article, MultipartFile coverImg) throws Exception{

        String content = article.getContent();
        List<TmpArticleImg> tmpArticleImgList = tmpArticleImgMapper.selectByExample(new TmpArticleImgExample());
        for (TmpArticleImg tmpArticleImg : tmpArticleImgList) {
            if (content.indexOf(tmpArticleImg.getPath()) == -1) {
                try {
                    File oldFile = new File("./" + tmpArticleImg.getPath());
                    if (oldFile.exists()) {
                        oldFile.delete();
                    }
                } catch (Exception e) {
                    log.error("无用文件删除失败，请关注：" + tmpArticleImg.getPath(), e);
                }
            }
        }
        try {
            tmpArticleImgMapper.deleteByTruncate();
        } catch (Exception e) {
            log.error("临时图片表清空失败！", e);
            throw e;
        }
        if(coverImg != null) {
            try {
                String fileName = coverImg.getOriginalFilename();
                String uuid = UUID.randomUUID().toString();
                String newFileName = uuid + "_" + fileName;
                File dFile = new File("./" + uploadCoverImgPath);
                File pFile = new File("./" + uploadCoverImgPath, newFileName);
                if (!dFile.exists()) {
                    dFile.mkdirs();
                }
                Utils.wirteFile(coverImg, pFile);
                String coverImgUrl = uploadCoverImgPath + newFileName;
                article.setCoverImg(coverImgUrl);
            } catch (Exception e) {
                log.error("文章封面图片保存失败！", e);
                throw e;
            }
        }

        try{
            if(article.getId() != null && article.getId()>0){
                ArticleExample example = new ArticleExample();
                example.createCriteria().andIdEqualTo(article.getId());
                article.setUpdateTime(new Date());
                articleMapper.updateByExampleSelective(article,example);
            }else{
                article.setCreateTime(new Date());
                article.setUpdateTime(new Date());
                articleMapper.insert(article);
            }
        }catch (Exception e){
            log.error("文章更新或插入失败："+article.toString(),e);
            throw e;
        }

    }

    @Override
    public List<Article> findArticlePage(ArticlePageDTO articlePageDTO) throws Exception {
        ArticleExample example = new ArticleExample();
        ArticleExample example1 = new ArticleExample();
        ArticleExample.Criteria cri = example.createCriteria();
        ArticleExample.Criteria cri1 = example1.createCriteria();
        if(articlePageDTO.getPageNum() != null && articlePageDTO.getPageSize() != null){
            example.setOrderByClause("create_time desc limit "+(articlePageDTO.getPageNum()-1)* articlePageDTO.getPageSize()+","+ articlePageDTO.getPageSize());
            example1.setOrderByClause("create_time desc limit "+(articlePageDTO.getPageNum()-1)* articlePageDTO.getPageSize()+","+ articlePageDTO.getPageSize());
        }else{
            example.setOrderByClause("create_time desc");
            example1.setOrderByClause("create_time desc");
        }
        if(articlePageDTO.getType() != null){
            List<Integer> types = new ArrayList<>();
            if(articlePageDTO.getType()==99){
                types.add(5);
                types.add(6);
                types.add(7);
            }else{
                types.add(articlePageDTO.getType());
            }
            cri.andTypeIn(types);
            cri1.andTypeIn(types);
        }
        if(articlePageDTO.getKeywords() != null && !"".equals(articlePageDTO.getKeywords())){
            cri.andTitleLike("%"+ articlePageDTO.getKeywords()+"%");
            cri1.andTitleLike("%"+ articlePageDTO.getKeywords()+"%");
        }
        cri.andIsTopEqualTo(0);
        List<Article> articles = articleMapper.selectByExample(example);
        cri1.andIsTopEqualTo(1);
        List<Article> articles1 = articleMapper.selectByExample(example1);
        if(articles != null && articles1 != null){
            articles.addAll(0,articles1);
            return articles;
        }else if(articles != null){
            return articles;
        }else if(articles1 != null){
            return articles1;
        }else{
            return new ArrayList<Article>();
        }

    }

    @Override
    public ArticleVO findArticleById(ArticleDTO param) throws Exception {
        ArticleVO articleVO = articleMapper.selectArticleDetail(param.getId(),param.getLoginUserId());
        return articleVO;
    }

    @Override
    public void addArcticleReadCount(ArticleDTO param) throws Exception {
        ArticleVO articleVO = articleMapper.selectArticleDetail(param.getId(),param.getLoginUserId());
        ArticleExample articleExample = new ArticleExample();
        articleExample.createCriteria().andIdEqualTo(param.getId());
        Article article = new Article();
        article.setReadCount(articleVO.getReadCount()+1);
        articleMapper.updateByExampleSelective(article,articleExample);
        if(param.getLoginUserId() != null){
            Browse browse = new Browse();
            browse.setArticleId(param.getId());
            browse.setUserId(param.getLoginUserId());
            browse.setIsVaild(1);
            browse.setCreateTime(new Date());
            browse.setUpdateTime(new Date());
            browseMapper.insertOrUpdate(browse);
        }
    }

    @Override
    public List<Article> mylook(ArticlePageDTO articlePageDTO) throws Exception {
        return articleMapper.selectBrowseList(articlePageDTO.getLoginUserId());
    }

    @Override
    public List<Article> mylike(ArticlePageDTO articlePageDTO) throws Exception {
        return articleMapper.selectLikeList(articlePageDTO.getLoginUserId());
    }
}
